import { useEffect, useState, useRef } from 'react';

import { Card, Typography, message } from 'antd';
import * as pdfjsLib from 'pdfjs-dist';
const { Title, Text } = Typography;
pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js';

const PDFViewer = (props) => {
    const { filePath } = props;

    const [pdfPages, setPdfPages] = useState([]);
    const [currentPage, setCurrentPage] = useState(0);
    const [loading, setLoading] = useState(false);

    const canvasRefs = useRef([]);

    useEffect(() => {
        loadPDF();
    }, [filePath])
    const loadPDF = async () => {
        try {
            setLoading(true);
            // const fileUrl = `file://${filePath.replace(/\\/g, '/')}`;
            const pdfDoc = await pdfjsLib.getDocument(filePath).promise;

            const pagePromises = Array.from({ length: pdf.numPages }, (_, i) =>
                pdf.getPage(i + 1).then((page) => {
                    const viewport = page.getViewport({ scale: 1.0 });
                    return { page, viewport, pageNumber: i + 1 };
                })
            );

            const pages = await Promise.all(pagePromises);
            setPdfPages(pages);
            // setQrPositions([]);
            setCurrentPage(0);
            setLoading(false);
        } catch (error) {
            message.error('PDF文件加载失败');
        } finally {
            setLoading(false);
        }
    }

    return (
        <Card title={`PDF预览 (共${pdfPages.length}页)`}>
            {pdfPages.length > 0 ? (
                <div>
                    <canvas
                        ref={canvasRefs}
                        style={{
                            border: '1px solid #d9d9d9',
                            cursor: 'crosshair',
                            maxWidth: '100%',
                            height: 'auto'
                        }}
                    />
                </div>
            ) : (
                <div style={{ textAlign: 'center', padding: '40px' }}>
                    <Text type="secondary">请先选择PDF文件</Text>
                </div>
            )}

        </Card>
    )

}

export default PDFViewer